//
//  XMGPhotoManger.m
//  BuDeJie16
//
//  Created by xiaomage on 16/7/15.
//  Copyright © 2016年 seemygo. All rights reserved.
//

#import "XMGPhotoManger.h"

@implementation XMGPhotoManger
+ (void)savePhoto:(UIImage *)image albumTitle:(NSString *)albumTitle completionHandler:(void(^)(BOOL success, NSError * error))completionHandler
{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 判断下是否已经存在相册,如果已经存在相册,保存到之前相册
        // 遍历系统相册,查找之前相册
        PHAssetCollection *album = [self fetchAlbumOfTitle:albumTitle];
        
        // 创建相册请求类
        PHAssetCollectionChangeRequest *assetCollectionChangeRequest;
        
        if (album) {
            // 获取相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:album];
        } else {
            // 1.创建自己相册 (相册请求类:创建相册)
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumTitle];
        }
        
        // 2.创建图片请求类
        PHAssetCreationRequest *assetCreationRequest =[PHAssetCreationRequest creationRequestForAssetFromImage:image];
        
        // 3.添加图片到相册中(相册请求类)
        // NSFastEnumeration:数组
        [assetCollectionChangeRequest addAssets:@[assetCreationRequest.placeholderForCreatedAsset]];
        
    } completionHandler:completionHandler];
    
}

+ (PHAssetCollection *)fetchAlbumOfTitle:(NSString *)albumTitle

{
    // 获取系统所有相册
    PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    // 遍历系统相册
    for (PHAssetCollection *assetCollection in result) {
        if ([assetCollection.localizedTitle isEqualToString:albumTitle]) {
            return assetCollection;
        }
        
    }
    return nil;
}


@end
